package com.example.animationmodule.lottieanimationview

import android.animation.Animator
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieCompositionFactory
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.utils.dp2px
import com.example.animationmodule.AnimationPath
import com.example.animationmodule.R
import com.example.animationmodule.databinding.ActivityLottieanimationviewBinding

@Route(path =AnimationPath.LottieAnimationView )
class LottieAnimationViewActivity:BaseActivity<ActivityLottieanimationviewBinding>() {
    private var index = 0;
    override fun getLayoutId(): Int {
        return R.layout.activity_lottieanimationview
    }

    override fun initView() {

    }

    override fun initListener() {

    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.action){
            MotionEvent.ACTION_DOWN ->{


            }
            MotionEvent.ACTION_UP->{
                addView(event.rawX,event.rawY,index)
                index ++
            }
        }

        return super.onTouchEvent(event)
    }

    private fun addView(x: Float, y: Float, index: Int) {
        Log.i("TAGaaa", "addView: $x")

        val animationView = LottieAnimationView(this)
        val layoutParams =
            ViewGroup.LayoutParams(dp2px(this,80), dp2px(this,80))
        animationView.layoutParams = layoutParams
        animationView.id = index


        animationView.progress = 0f
        animationView.imageAssetsFolder = "gift/"
        LottieCompositionFactory.fromRawRes(this, R.raw.voice_newcomer_guide_gift).addListener {
            animationView.setComposition(it)
            animationView.playAnimation()
        }
        animationView.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {

            }

            override fun onAnimationEnd(animation: Animator) {
                Log.i("TAGaaa", "onAnimationEnd: ")
                mBinding.llContains.removeView(animationView)
            }

            override fun onAnimationCancel(animation: Animator) {

            }

            override fun onAnimationRepeat(animation: Animator) {

            }

        })

        animationView.playAnimation()
        // animationView.layout(x.toInt(),y.toInt(),0,0)
        mBinding.llContains.addView(animationView)
       // mBinding.llContains.setPadding(px2Dp(x- dp2px(this,20)),px2Dp(y- dp2px(this,20)),0,0)
        animationView.translationX = x- dp2px(this,20)
        animationView.translationY = y-dp2px(this,100)

    }

   fun px2Dp(px :Float ) =(px/resources.displayMetrics.density+0.5).toInt()
}

